package util;

import java.awt.Component;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
* @author 作者:秋哲    E-mail:2810201146@qq.com:
* @version 创建时间：2020年4月29日 上午9:36:39
* @description: 
*/
public class CenterPanel extends JPanel{
	private double rate;//拉伸比例
	private JComponent c;//显示的组件
	private boolean strech;//是否拉伸
	public CenterPanel(double rate, boolean strech) {
		this.setLayout(null);
		this.rate = rate;
		this.strech = strech;
	}
	public CenterPanel(double rate) {
		this(rate,true);
	}
	
	public void repaint() {
		if(null != c) {
			Dimension containerSize = this.getSize();
			Dimension componentSize = c.getPreferredSize();
			if(strech) {
				c.setSize((int) (containerSize.width*rate) , (int) (containerSize.height * rate));
			}else {
				c.setSize(componentSize);
			}
			c.setLocation(containerSize.width / 2 - c.getSize().width/2, containerSize.height / 2 -c.getSize().height/2);
		}
		super.repaint();
	}
	
	public void show(JComponent p) {
		this.c = p;
		Component[] cs = getComponents();
		for(Component c:cs) {
			remove(c);
		}
		add(p);
		this.updateUI();
	}
	
	public static void main(String[] args) {
		JFrame f = new JFrame();
		f.setSize(200,200);
		f.setLocationRelativeTo(null);
		
		CenterPanel cp = new CenterPanel(0.85,true); //true 表示拉伸的意思
		f.setContentPane(cp);
		f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
		f.setVisible(true);
		
		JButton b = new JButton("11");
		
		cp.show(b);
		
		
	}
	
}
